package com.saku.uiprojecttest.views;
/**
 * Created by liumin on 2016-6-7.
 */


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

import com.saku.uiprojecttest.R;


/**
 * User: Missa
 * Date: 2016-06-07
 * Time: 16:17
 * Description:
 */
public class RoundedRatioImageView extends ImageView {
    private static final String TAG = RoundedRatioImageView.class.getSimpleName();

    private float mRatio;  // width : height
    private float mRadius;
    private boolean mIsCircle;
    private Bitmap mSrcBitmap;
    private Paint mPaint;

    public RoundedRatioImageView(Context context) {
        this(context, null);
    }

    public RoundedRatioImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundedRatioImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initResourceAndPaint(context, attrs);
    }

    private void initResourceAndPaint(Context context, AttributeSet attrs) {
        final TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RoundedRatioImageView);
        mRatio = ta.getFloat(R.styleable.RoundedRatioImageView_ratio, 0);
        mRadius = ta.getDimension(R.styleable.RoundedRatioImageView_radius, 0);
        mIsCircle = ta.getBoolean(R.styleable.RoundedRatioImageView_circle, false);
        int resourceId = ta.getResourceId(R.styleable.RoundedRatioImageView_android_src, R.drawable.default_flower);

        if (resourceId != 0) {
            mSrcBitmap = BitmapFactory.decodeResource(getResources(), resourceId);
        }

        ta.recycle();

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setFilterBitmap(true);
        mPaint.setDither(true);
    }


    /**
     * width : height
     *
     * @param ratio
     */
    public void setRatio(float ratio) {
        this.mRatio = ratio;
        if (mRatio != 0.0f) {
            invalidate();
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec - getPaddingLeft() - getPaddingRight());
        int height = MeasureSpec.getSize(heightMeasureSpec - getPaddingTop() - getPaddingBottom());

        // 宽 填充父控件 或具体指
        if (widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY && mRatio != 0.0f) {
            height = (int) (width / mRatio + 0.5f);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + getPaddingTop() + getPaddingBottom(), MeasureSpec.EXACTLY);
        } else if (widthMode != MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY && mRatio != 0.0f) {
            width = (int) (height * mRatio + 0.5f);
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(width + getPaddingLeft() + getPaddingRight(), MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Log.d(TAG, "onDraw: getWidth() : " + getWidth());
        if (getWidth() == 0 || getHeight() == 0){
            return;
        }
        int width = getWidth() - getPaddingLeft() - getPaddingRight();
        int height = getHeight() - getPaddingTop() - getPaddingBottom();

        Bitmap srcBitmap = convertDrawableToBitmap(getDrawable());

        mPaint.reset();
        final Rect rectSrc = new Rect(0, 0, srcBitmap.getWidth(), srcBitmap.getHeight());
        final Rect rectDest = new Rect(0,0,getWidth(),getHeight());
        canvas.drawBitmap(createRoundCornerBitmap(srcBitmap, mRadius), rectSrc, rectDest, mPaint);
    }

    private Bitmap createRoundCornerBitmap(Bitmap bitmapToDraw, float radius) {
        Bitmap output = Bitmap.createBitmap(bitmapToDraw.getWidth(), bitmapToDraw.getHeight(), Bitmap.Config.RGB_565);

        Canvas canvas = new Canvas(output);
        Rect rect = new Rect(0, 0, bitmapToDraw.getWidth(), bitmapToDraw.getHeight());
        RectF rectF = new RectF(rect);

        canvas.drawARGB(0, 0, 0, 0);
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawRoundRect(rectF, radius, radius, mPaint);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmapToDraw, rect, rect, mPaint);
        return output;
    }

    private Bitmap convertDrawableToBitmap(Drawable drawable) {
        if (drawable == null) {
            return mSrcBitmap;
        } else if (drawable instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            return bitmap;
        } else {
            Log.d(TAG, "convertDrawableToBitmap create ======== ");
            // 如果没有合适的bitmap， 用drawable创建一个bitmap
            Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
//            canvas = null;
            return bitmap;
        }
    }
}
